from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import CustomUserCreationForm, UserLoginForm

def register(request):
    if request.user.is_authenticated:
        return redirect('users:home')
        
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            messages.success(request, '注册成功！欢迎加入我们！')
            return redirect('users:home')
    else:
        form = CustomUserCreationForm()
    
    return render(request, 'users/register.html', {'form': form})

def user_login(request):
    if request.user.is_authenticated:
        return redirect('users:home')
        
    if request.method == 'POST':
        form = UserLoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                messages.success(request, f'欢迎回来，{username}！')
                # 获取next参数，如果存在则重定向到该页面
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url)
                return redirect('users:home')
            else:
                messages.error(request, '用户名或密码错误')
    else:
        form = UserLoginForm()
    
    return render(request, 'users/login.html', {'form': form})

@login_required
def profile(request):
    # 获取用户的订单历史
    orders = request.user.order_set.all().order_by('-created_at')
    return render(request, 'users/profile.html', {
        'user': request.user,
        'orders': orders
    })

def user_logout(request):
    logout(request)
    messages.success(request, '您已成功退出登录')
    return redirect('users:home')

def home(request):
    return render(request, 'index.html')

from django.contrib.auth.forms import UserChangeForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm

@login_required
def profile_view(request):
    if request.method == 'POST':
        form = UserChangeForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            messages.success(request, '资料更新成功！')
            return redirect('users:profile')
    else:
        form = UserChangeForm(instance=request.user)
    return render(request, 'users/profile.html', {'form': form})

@login_required
def password_change_view(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)  # 保持用户登录状态
            messages.success(request, '密码修改成功！')
            return redirect('users:profile')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'users/password_change.html', {'form': form})
